package com.shinhye.mobilelottery.net.protocol;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.xmlpull.v1.XmlSerializer;

import android.util.Log;
import android.util.Xml;

import com.shinhye.mobilelottery.ConstantValue;
import com.shinhye.mobilelottery.utils.DES;

/**
 * 协议体的封装
 * @author ShinHye
 * 2014-9-22 下午4:08:30
 */
public class Body {
	/*
	 * 	<body>
            <elements>
                  <element>
                         <lotteryid>118</lotteryid>
                         <issues>1</issues>
                  </element>
            </elements> 
     	</body>
	 */
	
	private List<Element> elements = new ArrayList<Element>();
	// 处理回复的节点
	private Oelement oelement = new Oelement();
	// body信息加密及解析存储的临时存储点
	private String bodyInfo;
	
	public void serializer(XmlSerializer serializer) {
		try {
			serializer.startTag(null, "body");
			serializer.startTag(null, "elements");

			for (Element element : elements) {
				element.serializer(serializer);
			}

			serializer.endTag(null, "elements");
			serializer.endTag(null, "body");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public Oelement getOelement() {
		return oelement;
	}

	public String getBodyInfo() {
		return bodyInfo;
	}
	
	public void setBodyInfo(String bodyInfo) {
		this.bodyInfo = bodyInfo;
	}


	public List<Element> getElements() {
		return elements;
	}

	/**
	 * 获取body未DES加密的信息
	 */
	public String getBody() {
		//要自己创建临时Xml序列化器，因为如果要传一个XmlSerializer进来，它里面会包含很多无用的信息，导致结果出错。
		XmlSerializer temp = Xml.newSerializer();
		StringWriter writer = new StringWriter();
		try {
			temp.setOutput(writer);
			this.serializer(temp);
			//一般都是通过EndDocument来flush xml，此处没有EndDocument，只能手动flush。
			temp.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return writer.toString();
	}

	/**
	 * 获取body的DES加密信息
	 */
	public String getBodyDES() {
		String body = getBody();
		Log.i("Body", body);
		//截取某一字符串(arg0)内，开始字符串(arg1)和结束字符串(arg2)之间的内容。
		body = StringUtils.substringBetween(body, "<body>", "</body>");
		String authcode = new DES().authcode(body, "DECODE",
				ConstantValue.DES_KEY);
		return authcode;
	}

}